﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Imaginecup.sprite.animation;
using Microsoft.Xna.Framework;
using Imaginecup.util.resourceMan;
using Microsoft.Xna.Framework.Graphics;
using imaginecup.util;
using Microsoft.Xna.Framework.Content;
using Imaginecup.shareData;

namespace Imaginecup.sprite
{
    public class AnimationSpriteByTexture:ISprite
    {    
        private List<String> m_TextureNameList;

        private int m_TextureCountX;

        private IAnimationIndexProvider m_AnimationIndex;

        private ContentManager m_Content;
        private Vector2 m_PrevIndex;

        private Texture2D m_Texture;


        public AnimationSpriteByTexture(IAnimationIndexProvider animationIndex)
        {
            m_AnimationIndex = animationIndex;
            m_TextureNameList = new List<String>();

            m_Content = new ContentManager(StateShareData.GetShareData().GetGame().Services);
            m_Content.RootDirectory = "Content";

            m_TextureCountX = 0;

            m_PrevIndex = new Vector2(-1, -1);
        }
      
        public void AddTextureName(String textureName)
        {
            m_TextureNameList.Add(textureName);
            m_TextureCountX++;
        }

        
        public void Draw(SpriteBatch spriteBatch, EntityInfo entityInfo)
        {           

            Vector2 indexV = m_AnimationIndex.GetAnimationIndex();

            int index = (int)(indexV.Y * m_TextureCountX + indexV.X);

            if( indexV.X != m_PrevIndex.X || indexV.Y != m_PrevIndex.Y )
            {

                m_Texture = ResourceMan.GetResourceMan().GetTexture(m_TextureNameList[index]);
                if (m_Texture == null)
                {                    
                    m_Texture = m_Content.Load<Texture2D>( m_TextureNameList[index] );
                    ResourceMan.GetResourceMan().SetTextureFrame(m_TextureNameList[index] , m_Texture);
                }
            }

            m_PrevIndex = indexV;

            spriteBatch.Begin();
            spriteBatch.Draw(m_Texture, new Rectangle((int)entityInfo.mPosition.X, (int)entityInfo.mPosition.Y,
                                                     (int)entityInfo.mSize.X, (int)entityInfo.mSize.Y),
                                      new Rectangle(0, 0, m_Texture.Width, m_Texture.Height),
                            Color.White);

            spriteBatch.End();
        }

        public void Release()
        {
            foreach(String textureKey in m_TextureNameList)
            {
                ResourceMan.GetResourceMan().Release(textureKey);
            }
            m_Content.Unload();
        }

    }
}
